package service

import (
	"context"
	log "github.com/micro/go-micro/v2/logger"
	"rpc-service/user/model"
	"rpc-service/user/proto/user"
	"rpc-service/user/repository"
)

type UserService struct {
}

func (u *UserService) Register(ctx context.Context, in *user.RegisterReq, out *user.RegisterResp) error {
	if users, err := repository.GetInstance().FindByName(in.UserName); err != nil {
		log.Error("FindByName err: ", err)
		out.State = &user.State{Code: 4000, Message: "FindByName err", Error: err.Error()}
		return err
	} else {
		if len(users)!=0 {
			out.State = &user.State{Code: 1001, Message: "用户名重复"}
			return nil
		}
		newUser := model.User{UserName: in.UserName,PassWord:in.PassWord,Gender:in.Gender}
		res, err := repository.GetInstance().Create(&newUser)
		if err!=nil {
			out.State = &user.State{Code: 5001, Message: "注册失败"}
			return nil
		}
		log.Info("UserService  Login", in, res)
		out.State = &user.State{Code: 0, Message: "注册完成"}
		out.User = &user.User{UserName: res.UserName,Id:res.ID}
		return nil
	}
}

func (u *UserService) Login(ctx context.Context, in *user.LoginReq, out *user.LoginResp) error {
	if users, err := repository.GetInstance().FindByName(in.UserName); err != nil {
		log.Error("FindByName err: ", err)
		out.State = &user.State{Code: 4000, Message: "FindByName err", Error: err.Error()}
		return err
	} else {
		if len(users)==0 {
			out.State = &user.State{Code: 1000, Message: "该玩家不存在"}
			return nil
		}
		uInfo := users[0]
		if uInfo.PassWord != in.PassWord {
			out.State = &user.State{Code: 1001, Message: "密码错误"}
			return nil
		}
		out.State = &user.State{Code: 0, Message: "OK"}
		out.User = &user.User{UserName: in.UserName, PassWord: in.PassWord,Id:uInfo.ID}
		log.Info("UserService  Login", in)
		return nil
	}
}
